<template>
  <div class="note-detail-view" v-loading="loading">
    <div class="note-container" v-if="noteDetail">
      <!-- 笔记头部 -->
      <div class="note-header">
        <h1 class="note-title">{{ noteDetail.title }}</h1>
        
        <div class="note-meta">
          <div class="meta-left">
            <div class="author-info">
              <el-avatar :size="40" :src="noteDetail.userAvatar">
                {{ noteDetail.userName?.charAt(0) }}
              </el-avatar>
              <div class="author-details">
                <span class="author-name">{{ noteDetail.userName }}</span>
                <span class="publish-time">{{ formatDate(noteDetail.createTime) }}</span>
              </div>
            </div>
          </div>
          
          <div class="meta-right">
            <el-tag v-if="noteDetail.categoryName" type="info">
              {{ noteDetail.categoryName }}
            </el-tag>
            <el-tag v-if="noteDetail.type === 'daily'" type="success">日常笔记</el-tag>
            <el-tag v-if="noteDetail.type === 'document'" type="primary">文档笔记</el-tag>
          </div>
        </div>
      </div>

      <!-- 笔记内容 -->
      <div class="note-content">
        <div class="content-body" v-html="noteDetail.content"></div>
        
        <!-- 标签 -->
        <div class="note-tags" v-if="noteDetail.tags && noteDetail.tags.length > 0">
          <h4>标签</h4>
          <div class="tags-list">
            <el-tag
              v-for="tag in noteDetail.tags"
              :key="tag"
              effect="plain"
              @click="searchByTag(tag)"
            >
              {{ tag }}
            </el-tag>
          </div>
        </div>

        <!-- 附件 -->
        <div class="note-attachments" v-if="noteDetail.attachments && noteDetail.attachments.length > 0">
          <h4>附件</h4>
          <div class="attachments-list">
            <div 
              v-for="attachment in noteDetail.attachments"
              :key="attachment.id"
              class="attachment-item"
              @click="downloadAttachment(attachment)"
            >
              <el-icon><Document /></el-icon>
              <span>{{ attachment.fileName }}</span>
              <span class="file-size">({{ formatFileSize(attachment.fileSize) }})</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 操作栏 -->
      <div class="note-actions">
        <div class="action-buttons">
          <el-button 
            :type="isLiked ? 'primary' : 'default'"
            :icon="Star"
            @click="toggleLike"
            :loading="likeLoading"
          >
            {{ isLiked ? '已点赞' : '点赞' }} ({{ likeCount }})
          </el-button>
          
          <el-button 
            :type="isFavorited ? 'warning' : 'default'"
            :icon="Collection"
            @click="toggleFavorite"
            :loading="favoriteLoading"
          >
            {{ isFavorited ? '已收藏' : '收藏' }} ({{ favoriteCount }})
          </el-button>
          
          <el-button :icon="Share" @click="shareNote">
            分享
          </el-button>
        </div>
        
        <div class="view-count">
          <el-icon><View /></el-icon>
          <span>{{ noteDetail.viewCount || 0 }} 次浏览</span>
        </div>
      </div>

      <!-- 评论区 -->
      <div class="comments-section">
        <h3>评论 ({{ commentCount }})</h3>
        
        <!-- 发表评论 -->
        <div class="comment-form" v-if="userStore.isLoggedIn">
          <el-input
            v-model="newComment"
            type="textarea"
            :rows="3"
            placeholder="写下你的评论..."
            maxlength="500"
            show-word-limit
          />
          <div class="comment-actions">
            <el-button type="primary" @click="submitComment" :loading="commentSubmitting">
              发表评论
            </el-button>
          </div>
        </div>
        
        <div class="login-tip" v-else>
          <p>
            <router-link to="/login">登录</router-link> 后可以发表评论
          </p>
        </div>

        <!-- 评论列表 -->
        <div class="comments-list" v-loading="commentsLoading">
          <div v-if="(!comments || comments.length === 0) && !commentsLoading" class="no-comments">
            暂无评论，快来抢沙发吧！
          </div>
          
          <div v-for="comment in (comments || [])" :key="comment.id" class="comment-item">
            <div class="comment-avatar">
              <el-avatar :size="36" :src="comment.userAvatar">
                {{ comment.userName?.charAt(0) }}
              </el-avatar>
            </div>
            
            <div class="comment-content">
              <div class="comment-header">
                <span class="comment-author">{{ comment.userName }}</span>
                <span class="comment-time">{{ formatDate(comment.createTime) }}</span>
              </div>
              
              <div class="comment-text">{{ comment.content }}</div>
              
              <div class="comment-actions">
                <el-button 
                  text 
                  size="small"
                  :type="comment.isLiked ? 'primary' : 'default'"
                  @click="toggleCommentLike(comment)"
                >
                  <el-icon><Star /></el-icon>
                  {{ comment.likeCount || 0 }}
                </el-button>
                
                <el-button text size="small" @click="replyToComment(comment)">
                  回复
                </el-button>
                
                <el-button 
                  v-if="userStore.userInfo?.id === comment.userId"
                  text 
                  size="small" 
                  type="danger"
                  @click="deleteComment(comment)"
                >
                  删除
                </el-button>
              </div>
            </div>
          </div>
        </div>

        <!-- 加载更多评论 -->
        <div class="load-more" v-if="hasMoreComments">
          <el-button @click="loadMoreComments" :loading="commentsLoading">
            加载更多评论
          </el-button>
        </div>
      </div>
    </div>

    <!-- 推荐笔记 -->
    <div class="recommended-notes" v-if="recommendedNotes.length > 0">
      <h3>相关推荐</h3>
      <div class="recommended-list">
        <div 
          v-for="note in recommendedNotes"
          :key="note.id"
          class="recommended-item"
          @click="goToNote(note.id)"
        >
          <h4>{{ note.title }}</h4>
          <p>{{ note.summary }}</p>
          <div class="recommended-meta">
            <span>{{ note.userName }}</span>
            <span>{{ formatDate(note.createTime) }}</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Star, 
  Collection, 
  Share, 
  View, 
  Document 
} from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import { 
  getNoteDetail, 
  getRecommendedNotes 
} from '@/api/note'
import { 
  toggleNoteLike, 
  toggleNoteFavorite, 
  checkLikeStatus, 
  checkFavoriteStatus,
  addComment,
  getNoteComments,
  toggleCommentLike,
  deleteComment as deleteCommentApi
} from '@/api/interaction'
import type { 
  NoteDaily, 
  NoteDocument, 
  NoteComment, 
  CommentQuery 
} from '@/types/api'
import dayjs from 'dayjs'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()

// 响应式数据
const loading = ref(false)
const noteDetail = ref<NoteDaily | NoteDocument | null>(null)
const recommendedNotes = ref<(NoteDaily | NoteDocument)[]>([])

// 交互状态
const isLiked = ref(false)
const isFavorited = ref(false)
const likeCount = ref(0)
const favoriteCount = ref(0)
const likeLoading = ref(false)
const favoriteLoading = ref(false)

// 评论相关
const comments = ref<NoteComment[]>([])
const newComment = ref('')
const commentCount = ref(0)
const commentsLoading = ref(false)
const commentSubmitting = ref(false)
const hasMoreComments = ref(false)
const commentQuery = reactive<CommentQuery>({
  noteId: 0,
  noteType: 'daily', // 默认为daily，会在获取笔记详情后更新
  pageNum: 1,
  pageSize: 10
})

// 计算属性
const noteId = computed(() => Number(route.params.id))

// 获取笔记详情
const getNoteDetailData = async () => {
  loading.value = true
  try {
    const response = await getNoteDetail(noteId.value)
    if (response.code === 200) {
      noteDetail.value = response.data
      likeCount.value = response.data.likeCount || 0
      favoriteCount.value = response.data.favoriteCount || 0
      commentCount.value = response.data.commentCount || 0
      
      // 设置评论查询的笔记类型
      commentQuery.noteType = response.data.noteType || 'daily'
      
      // 检查点赞和收藏状态
      if (userStore.isLoggedIn) {
        checkInteractionStatus()
      }
    } else {
      ElMessage.error(response.msg || '获取笔记详情失败')
    }
  } catch (error) {
    console.error('获取笔记详情失败:', error)
    ElMessage.error('获取笔记详情失败')
  } finally {
    loading.value = false
  }
}

// 检查交互状态
const checkInteractionStatus = async () => {
  try {
    const [likeResponse, favoriteResponse] = await Promise.all([
      checkLikeStatus(noteId.value),
      checkFavoriteStatus(noteId.value)
    ])
    
    if (likeResponse.code === 200) {
      isLiked.value = likeResponse.data
    }
    
    if (favoriteResponse.code === 200) {
      isFavorited.value = favoriteResponse.data
    }
  } catch (error) {
    console.error('检查交互状态失败:', error)
  }
}

// 获取推荐笔记
const getRecommendedNotesData = async () => {
  try {
    const response = await getRecommendedNotes(noteId.value)
    if (response.code === 200) {
      recommendedNotes.value = response.data
    }
  } catch (error) {
    console.error('获取推荐笔记失败:', error)
  }
}

// 获取评论列表
const getComments = async (reset = false) => {
  if (reset) {
    commentQuery.pageNum = 1
    comments.value = []
  }
  
  commentsLoading.value = true
  try {
    const response = await getNoteComments(commentQuery)
    if (response.code === 200 && response.data && response.data.rows) {
      if (reset) {
        comments.value = response.data.rows || []
      } else {
        comments.value.push(...(response.data.rows || []))
      }
      hasMoreComments.value = comments.value.length < (response.data.total || 0)
    } else {
      if (reset) {
        comments.value = []
      }
      hasMoreComments.value = false
    }
  } catch (error) {
    console.error('获取评论失败:', error)
    if (reset) {
      comments.value = []
    }
    hasMoreComments.value = false
  } finally {
    commentsLoading.value = false
  }
}

// 点赞切换
const toggleLike = async () => {
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }
  
  likeLoading.value = true
  try {
    const response = await toggleNoteLike(noteId.value)
    if (response.code === 200) {
      isLiked.value = !isLiked.value
      likeCount.value += isLiked.value ? 1 : -1
      ElMessage.success(isLiked.value ? '点赞成功' : '取消点赞')
    } else {
      ElMessage.error(response.msg || '操作失败')
    }
  } catch (error) {
    console.error('点赞操作失败:', error)
    ElMessage.error('操作失败')
  } finally {
    likeLoading.value = false
  }
}

// 收藏切换
const toggleFavorite = async () => {
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }
  
  favoriteLoading.value = true
  try {
    const response = await toggleNoteFavorite(noteId.value)
    if (response.code === 200) {
      isFavorited.value = !isFavorited.value
      favoriteCount.value += isFavorited.value ? 1 : -1
      ElMessage.success(isFavorited.value ? '收藏成功' : '取消收藏')
    } else {
      ElMessage.error(response.msg || '操作失败')
    }
  } catch (error) {
    console.error('收藏操作失败:', error)
    ElMessage.error('操作失败')
  } finally {
    favoriteLoading.value = false
  }
}

// 分享笔记
const shareNote = () => {
  const url = window.location.href
  navigator.clipboard.writeText(url).then(() => {
    ElMessage.success('链接已复制到剪贴板')
  }).catch(() => {
    ElMessage.error('复制失败')
  })
}

// 提交评论
const submitComment = async () => {
  if (!newComment.value.trim()) {
    ElMessage.warning('请输入评论内容')
    return
  }
  
  commentSubmitting.value = true
  try {
    const response = await addComment({
      noteId: noteId.value,
      content: newComment.value.trim()
    })
    
    if (response.code === 200) {
      ElMessage.success('评论发表成功')
      newComment.value = ''
      commentCount.value++
      getComments(true) // 重新加载评论
    } else {
      ElMessage.error(response.msg || '评论发表失败')
    }
  } catch (error) {
    console.error('评论发表失败:', error)
    ElMessage.error('评论发表失败')
  } finally {
    commentSubmitting.value = false
  }
}

// 评论点赞
const toggleCommentLike = async (comment: NoteComment) => {
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录')
    return
  }
  
  try {
    const response = await toggleCommentLike(comment.id)
    if (response.code === 200) {
      comment.isLiked = !comment.isLiked
      comment.likeCount = (comment.likeCount || 0) + (comment.isLiked ? 1 : -1)
    }
  } catch (error) {
    console.error('评论点赞失败:', error)
  }
}

// 删除评论
const deleteComment = async (comment: NoteComment) => {
  try {
    await ElMessageBox.confirm('确定要删除这条评论吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await deleteCommentApi(comment.id)
    if (response.code === 200) {
      ElMessage.success('评论删除成功')
      commentCount.value--
      getComments(true) // 重新加载评论
    } else {
      ElMessage.error(response.msg || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除评论失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 回复评论
const replyToComment = (comment: NoteComment) => {
  newComment.value = `@${comment.userName} `
}

// 加载更多评论
const loadMoreComments = () => {
  commentQuery.pageNum++
  getComments()
}

// 标签搜索
const searchByTag = (tag: string) => {
  router.push(`/search?keyword=${encodeURIComponent(tag)}`)
}

// 跳转到笔记
const goToNote = (id: number) => {
  // 在详情页中推荐的笔记应该也是相同类型的
  const currentType = route.params.type || 'daily'
  router.push(`/note/${currentType}/${id}`)
}

// 下载附件
const downloadAttachment = (attachment: any) => {
  // 实现附件下载逻辑
  window.open(attachment.fileUrl, '_blank')
}

// 格式化日期
const formatDate = (date: string) => {
  return dayjs(date).format('YYYY-MM-DD HH:mm')
}

// 格式化文件大小
const formatFileSize = (size: number) => {
  if (size < 1024) return size + ' B'
  if (size < 1024 * 1024) return (size / 1024).toFixed(1) + ' KB'
  return (size / (1024 * 1024)).toFixed(1) + ' MB'
}

// 页面初始化
onMounted(async () => {
  commentQuery.noteId = noteId.value
  await getNoteDetailData()
  getRecommendedNotesData()
  getComments(true)
})
</script>

<style scoped>
.note-detail-view {
  max-width: 1000px;
  margin: 0 auto;
  padding: 20px;
}

.note-container {
  background: white;
  border-radius: 8px;
  padding: 30px;
  margin-bottom: 30px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.note-header {
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
}

.note-title {
  font-size: 2.2rem;
  color: #303133;
  margin-bottom: 20px;
  line-height: 1.4;
}

.note-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.author-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.author-details {
  display: flex;
  flex-direction: column;
}

.author-name {
  font-weight: 500;
  color: #303133;
}

.publish-time {
  font-size: 0.9rem;
  color: #909399;
}

.meta-right {
  display: flex;
  gap: 10px;
}

.note-content {
  margin-bottom: 30px;
}

.content-body {
  line-height: 1.8;
  color: #303133;
  font-size: 1.1rem;
}

.content-body :deep(h1),
.content-body :deep(h2),
.content-body :deep(h3),
.content-body :deep(h4),
.content-body :deep(h5),
.content-body :deep(h6) {
  margin: 20px 0 15px 0;
  color: #303133;
}

.content-body :deep(p) {
  margin-bottom: 15px;
}

.content-body :deep(code) {
  background: #f5f7fa;
  padding: 2px 6px;
  border-radius: 4px;
  font-family: 'Courier New', monospace;
}

.content-body :deep(pre) {
  background: #f5f7fa;
  padding: 15px;
  border-radius: 8px;
  overflow-x: auto;
  margin: 15px 0;
}

/* Quill 编辑器代码块样式 */
.content-body :deep(.ql-code-block-container) {
  background: #282c34;
  border: 1px solid #3e4451;
  border-radius: 8px;
  padding: 20px;
  margin: 20px 0;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', 'Courier New', monospace;
  font-size: 14px;
  overflow-x: auto;
  position: relative;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.content-body :deep(.ql-code-block-container::before) {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 30px;
  background: linear-gradient(90deg, #ff5f56 0%, #ffbd2e 33%, #27ca3f 66%);
  border-radius: 8px 8px 0 0;
  margin: -1px -1px 0 -1px;
}

.content-body :deep(.ql-code-block-container::after) {
  content: '';
  position: absolute;
  top: 8px;
  left: 15px;
  width: 12px;
  height: 12px;
  border-radius: 50%;
  background: #ff5f56;
  box-shadow: 20px 0 0 #ffbd2e, 40px 0 0 #27ca3f;
}

.content-body :deep(.ql-code-block) {
  margin: 0;
  line-height: 1.6;
  white-space: pre-wrap;
  color: #abb2bf;
  background: transparent;
  border: none;
  padding: 30px 0 0 0;
  font-family: inherit;
  font-size: 14px;
  display: block;
}

/* 代码块语法高亮样式 */
.content-body :deep(.ql-code-block-container .ql-code-block) {
  color: #abb2bf;
}

/* 为不同类型的代码添加语法高亮 */
.content-body :deep(.ql-code-block-container[data-language="javascript"] .ql-code-block),
.content-body :deep(.ql-code-block-container[data-language="js"] .ql-code-block) {
  color: #e06c75;
}

.content-body :deep(.ql-code-block-container[data-language="python"] .ql-code-block) {
  color: #61afef;
}

.content-body :deep(.ql-code-block-container[data-language="java"] .ql-code-block) {
  color: #e06c75;
}

.content-body :deep(.ql-code-block-container[data-language="css"] .ql-code-block) {
  color: #c678dd;
}

.content-body :deep(.ql-code-block-container[data-language="html"] .ql-code-block) {
  color: #d19a66;
}

.content-body :deep(.ql-code-block-container[data-language="sql"] .ql-code-block) {
  color: #61afef;
}

.content-body :deep(.ql-code-block-container[data-language="yaml"] .ql-code-block),
.content-body :deep(.ql-code-block-container[data-language="yml"] .ql-code-block) {
  color: #98c379;
}

/* Docker Compose 和配置文件特殊样式 */
.content-body :deep(.ql-code-block-container[data-language="docker"] .ql-code-block),
.content-body :deep(.ql-code-block-container[data-language="dockerfile"] .ql-code-block) {
  color: #56b6c2;
}

/* 通用配置文件样式 */
.content-body :deep(.ql-code-block) {
  /* 关键字高亮 */
  background: transparent;
}

/* 为代码块添加行号效果 */
.content-body :deep(.ql-code-block-container) {
  counter-reset: line-number;
}

.content-body :deep(.ql-code-block) {
  counter-increment: line-number;
  position: relative;
  padding-left: 50px;
}

.content-body :deep(.ql-code-block::before) {
  content: counter(line-number);
  position: absolute;
  left: -40px;
  top: 0;
  color: #5c6370;
  font-size: 12px;
  line-height: inherit;
  text-align: right;
  width: 30px;
  user-select: none;
}

.note-tags,
.note-attachments {
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.note-tags h4,
.note-attachments h4 {
  margin-bottom: 15px;
  color: #303133;
}

.tags-list {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.tags-list .el-tag {
  cursor: pointer;
}

.attachments-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.attachment-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px;
  background: #f8f9fa;
  border-radius: 6px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.attachment-item:hover {
  background: #e9ecef;
}

.file-size {
  color: #909399;
  font-size: 0.9rem;
}

.note-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 0;
  border-top: 1px solid #ebeef5;
  border-bottom: 1px solid #ebeef5;
}

.action-buttons {
  display: flex;
  gap: 15px;
}

.view-count {
  display: flex;
  align-items: center;
  gap: 5px;
  color: #909399;
}

.comments-section {
  margin-top: 30px;
}

.comments-section h3 {
  margin-bottom: 20px;
  color: #303133;
}

.comment-form {
  margin-bottom: 30px;
}

.comment-actions {
  margin-top: 10px;
  text-align: right;
}

.login-tip {
  text-align: center;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 6px;
  margin-bottom: 30px;
}

.login-tip a {
  color: #409eff;
  text-decoration: none;
}

.comments-list {
  min-height: 200px;
}

.no-comments {
  text-align: center;
  color: #909399;
  padding: 40px 0;
}

.comment-item {
  display: flex;
  gap: 12px;
  padding: 20px 0;
  border-bottom: 1px solid #f0f0f0;
}

.comment-content {
  flex: 1;
}

.comment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.comment-author {
  font-weight: 500;
  color: #303133;
}

.comment-time {
  color: #909399;
  font-size: 0.9rem;
}

.comment-text {
  color: #606266;
  line-height: 1.6;
  margin-bottom: 10px;
}

.comment-actions {
  display: flex;
  gap: 15px;
}

.load-more {
  text-align: center;
  margin-top: 20px;
}

.recommended-notes {
  background: white;
  border-radius: 8px;
  padding: 30px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.recommended-notes h3 {
  margin-bottom: 20px;
  color: #303133;
}

.recommended-list {
  display: grid;
  gap: 15px;
}

.recommended-item {
  padding: 15px;
  border: 1px solid #ebeef5;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s;
}

.recommended-item:hover {
  border-color: #409eff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
}

.recommended-item h4 {
  margin-bottom: 8px;
  color: #303133;
  font-size: 1.1rem;
}

.recommended-item p {
  color: #606266;
  margin-bottom: 10px;
  font-size: 0.9rem;
}

.recommended-meta {
  display: flex;
  justify-content: space-between;
  font-size: 0.8rem;
  color: #909399;
}

@media (max-width: 768px) {
  .note-detail-view {
    padding: 10px;
  }
  
  .note-container {
    padding: 20px;
  }
  
  .note-title {
    font-size: 1.8rem;
  }
  
  .note-meta {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }
  
  .note-actions {
    flex-direction: column;
    gap: 15px;
    align-items: flex-start;
  }
  
  .comment-item {
    flex-direction: column;
    gap: 10px;
  }
  
  .comment-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 5px;
  }
}
</style>